const WebSocket = require('ws');
const crypto = require('crypto');
const { URLSearchParams } = require('url');
// 以下内容请替换成您自己申请的讯飞星火密钥
let appid = ""
let api_key =""
let api_secret = ""

const gpt_url = "ws://spark-api.xf-yun.com/v1.1/chat"

if (api_secret.length === 0) {
    const fs = require('fs');
    fs.readFile('xing_huo.json', 'utf8', (err, data) => {
        if (err) {
            console.error('Error:', err);
            return;
        }

        try {
            const json = JSON.parse(data);
            // 在这里可以处理 JSON 数据
            appid = json.XINGHUO_APPID
            api_key = json.XINGHUO_API_KEY
            api_secret = json.XINGHUO_API_SECRET
        } catch (error) {
            console.error('Error parsing JSON:', error);
        }
    });

}

class Ws_Param {
    constructor(APPID, APIKey, APISecret, gpt_url) {
        this.APPID = APPID;
        this.APIKey = APIKey;
        this.APISecret = APISecret;
        this.url = new URL(gpt_url);
        this.path = this.url.pathname;
        this.gpt_url = gpt_url;
    }
    // 生成url
    createUrl() {
        // 生成RFC1123格式的时间戳
        const now = new Date();
        const date = now.toUTCString();
        const signatureOrigin = `host: ${this.url.host}\ndate: ${date}\nGET ${this.path} HTTP/1.1`;
        // 进行hmac-sha256进行加密
        const signature = crypto
        .createHmac('sha256', this.APISecret)
        .update(signatureOrigin)
        .digest('base64');
        const authorizationOrigin = `api_key="${this.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`;
        const authorization = Buffer.from(authorizationOrigin).toString('base64');
        const params = new URLSearchParams({
            authorization,
            date,
            host: this.url.host,
        });
        const url = `${this.gpt_url}?${params.toString()}`;
        return url;
    }
}


function genParams(appid, question) {
    const data = {
        header: {
            app_id: appid,
            uid: '1234',
        },
        parameter: {
            chat: {
                domain: 'general',
                random_threshold: 0.5,
                max_tokens: 2048,
                auditing: 'default',
            },
        },
        payload: {
            message: {
                text: [
                { role: 'user', content: question },
                ],
            },
        },
    };
    return data;
}

function init(host, port) {
    // 创建WebSocket服务器，监听指定的端口
    const wss = new WebSocket.Server({ port: port + 7000, host: host });
    // 监听连接建立事件
    wss.on('connection', function connection(vws) {

        function onMessage(message) {
            const data = JSON.parse(message);
            const code = data.header.code;
            if (code !== 0) {
                console.log(`请求错误: ${code}, ${data}`);
                this.close();
            } else {
                const choices = data.payload.choices;
                const status = choices.status;
                const content = choices.text[0].content;
                vws.send(content); // 转发信息
                if (status === 2) {
                    this.close();
                }
            }
        }

        function onClose() {
            vws.send("finish");
        }
        
        function sendMsgXH(question) {
            const wsParam = new Ws_Param(appid, api_key, api_secret, gpt_url);
            const wsUrl = wsParam.createUrl();
            let xinghuows = new WebSocket(wsUrl);
            xinghuows.appid = appid;
            xinghuows.question = question;
            xinghuows.on('open', () => {xinghuows.send(JSON.stringify(genParams(xinghuows.appid, xinghuows.question)))});
            xinghuows.on('message', (message) => onMessage.call(xinghuows, message));
            xinghuows.on('error', (error) => {console.error('### XH error:', error)});
            xinghuows.on('close', () => onClose());
        }

        // 监听接收到客户端消息事件
        vws.on('message', function incoming(message) {
            sendMsgXH(message.toString())
        });

        // 监听连接关闭事件
        vws.on('close', function close() {
            console.log('WebSocket连接已关闭');
        });
    });
}

exports.init = init